#coding: UTF-8
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
import re
print sys.getdefaultencoding()
reload(sys)
sys.setdefaultencoding('utf-8')
print sys.getdefaultencoding()
import chardet
from lib.pyhk import *
import locale



def echo(str1):
    str = str1
    print chardet.detect(str)
    if isinstance(str, unicode):
        # s=u"中文"
        return str.encode('utf-8')
    else:
        # s="中文"
        return unicode(str).decode('gbk')

#融合0和2内容，触发弹出

class ani(QWidget):
    def __init__(self):
        super(ani, self).__init__()
        self.layout = QGridLayout()
        self.OrigHeight = 250
        self.ChangeHeight = 250
        self.setGeometry(QRect(200, 200, 350, self.OrigHeight))  # 在X=500， Y=400 ， Length=150 ,   Height=50
        self.setWindowFlags(Qt.CustomizeWindowHint | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
        self.setAcceptDrops(True)
        #self.btn = QPushButton(u'展开', self)
        #self.btn.setGeometry(10, 10, 60, 35)
        #delaySpinBoxLabel = QLabel(u"扫码结果:",self)
        #self.layout.addWidget(delaySpinBoxLabel, 1, 0)
        self.nameLine = QLineEdit(self)
        #self.mycode = locale.getpreferredencoding()
        #code = QTextCodec.codecForName(self.mycode)
        #QTextCodec.setCodecForLocale(code)
        #QTextCodec.setCodecForTr(code)
        #QTextCodec.setCodecForCStrings(code)
        self.nameLine.setMaximumWidth(250)
        self.setLayout(self.layout)
        #self.delaySpinBoxLabel.setGeometry(10, 10, 60, 20)
        #self.nameLine.setGeometry(70, 10, 160, 20)
        self.layout.addWidget(self.nameLine, 1,0,1,2)
        self.machine = QStateMachine()
        #self.nameLine.setPlaceholderText(u"请扫码输入")
        self.installEventFilter(self)
        #self.shortcut = QShortcut(QKeySequence("Ctrl+T"), self,activated = lambda: (self.on_open() , self.nameLine.setFocus()))
        #self.shortcut.activated.connect(self.on_open)
        #self.connect(self.btn, SIGNAL('clicked()'), self.change)
        self.connect(self.nameLine, SIGNAL('textChanged(QString)'), self.txtupdate)
        self.contextMenu = QMenu(self)
        self.actionA = self.contextMenu.addAction(QIcon("images/0.png"), u'|  退出')
        self.connect(self.actionA, SIGNAL('enterEvent()'), self.close)
        self.names = locals()
        self.createContextMenu()
        # 创建hotkey句柄
        hot_handle = pyhk()
        hot_handle.addHotkey(['Ctrl', 'T'], self.hkfunc)

    def createContextMenu(self):
        '''''
        创建右键菜单
        '''
        # 必须将ContextMenuPolicy设置为Qt.CustomContextMenu
        # 否则无法使用customContextMenuRequested信号
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showContextMenu)

        # 创建QMenu
        self.contextMenu = QMenu(self)
        self.actionA = self.contextMenu.addAction(u'关闭')
        #self.actionB = self.contextMenu.addAction(u'动作B')
        #self.actionC = self.contextMenu.addAction(u'动作C')
        # 将动作与处理函数相关联
        # 这里为了简单，将所有action与同一个处理函数相关联，
        # 当然也可以将他们分别与不同函数关联，实现不同的功能
        self.actionA.triggered.connect(self.close)
        #self.actionB.triggered.connect(self.actionHandler)
        #self.actionB.triggered.connect(self.actionHandler)

    def showContextMenu(self, pos):
        '''''
        右键点击时调用的函数
        '''
        # 菜单显示前，将它移动到鼠标点击的位置
        self.contextMenu.move(self.pos() + pos)
        self.contextMenu.show()

    def actionHandler(self):
        '''''
        菜单中的具体action调用的函数
        '''
        print 'action handler'

    def hkfunc(self):
        print 'action hkfunc'
        self.hide()
        self.show()
        self.raise_()
        self.setWindowOpacity(1)
        self.nameLine.selectAll()
        self.nameLine.setFocus()
        self.activateWindow()
        self.windowActivationChange(True)

    def lineUpdate(self, sList):
        btncont = self.layout.count()
        print btncont
        for j in range(1,100):
            try:
                self.layout.removeWidget(self.names['widget%s' % j])
                self.names['widget%s' % j].deleteLater()
                self.names['widget%s' % j] = None
                self.layout.removeWidget(self.names['button%s' % j])
                self.names['button%s' % j].deleteLater()
                self.names['button%s' % j] = None
            except:
                break
        self.nameLine.setMaximumWidth(250)
        print u"展示列表：",sList
        for i in range(1, len(sList)):
            print sList[i]
            if sList[i].strip() == '':
                continue
            self.names['widget%s' % i] = QLineEdit(self)
            self.names['widget%s' % i].setText(sList[i])
            self.names['widget%s' % i].setMaximumWidth(250)
            self.layout.addWidget(self.names['widget%s' % i],i+1,0)
            self.names['button%s' % i] = QPushButton(u'复制',self)
            if i==1:
                self.connect(self.names['button%s' % i], SIGNAL("clicked()"), self.copystr1)
            if i==2:
                self.connect(self.names['button%s' % i], SIGNAL("clicked()"), self.copystr2)
            if i==3:
                self.connect(self.names['button%s' % i], SIGNAL("clicked()"), self.copystr3)
            if i==4:
                self.connect(self.names['button%s' % i], SIGNAL("clicked()"), self.copystr4)
            if i==5:
                self.connect(self.names['button%s' % i], SIGNAL("clicked()"), self.copystr5)
            if i==6:
                self.connect(self.names['button%s' % i], SIGNAL("clicked()"), self.copystr6)
            if i==7:
                self.connect(self.names['button%s' % i], SIGNAL("clicked()"), self.copystr7)
            if i==8:
                self.connect(self.names['button%s' % i], SIGNAL("clicked()"), self.copystr8)
            if i==9:
                self.connect(self.names['button%s' % i], SIGNAL("clicked()"), self.copystr9)
            if i==10:
                self.connect(self.names['button%s' % i], SIGNAL("clicked()"), self.copystr10)
            #self.names['button%s' % i].clicked.connect(lambda: self.copystr(i))
            self.layout.addWidget(self.names['button%s' % i], i + 1, 1)

    def copystr1(self):
        self.copystr(1)

    def copystr2(self):
        self.copystr(2)
    def copystr3(self):
        self.copystr(3)
    def copystr4(self):
        self.copystr(4)
    def copystr5(self):
        self.copystr(5)
    def copystr6(self):
        self.copystr(6)
    def copystr7(self):
        self.copystr(7)
    def copystr8(self):
        self.copystr(8)
    def copystr9(self):
        self.copystr(9)
    def copystr10(self):
        self.copystr(10)
    def copystr(self,str):
        my_txt = unicode(self.names['widget%s' % str].text())
        print str,u"复制到粘贴板中:",my_txt
        clipboard = QApplication.clipboard()
        clipboard.setText(my_txt)

    def txtupdate(self,QString):
        self.setWindowOpacity(1)
        #print 'txtupdate:',QString.toUtf8()
        tmp_str = unicode(QString)
        #解析输入内容
        #re.split('，', QString)
        strList = []
        #信用代码
        if tmp_str.find('，')>-1:
            #print 'afei:',tmp_str[9:26]
            strList = re.split(u'，', tmp_str)
            strList = re.split(u'：', strList[0])
            #strList.remove(u'统一社会信用代码')
        #解析
        if tmp_str.find('；')>-1:
            strList = re.split(u'；', tmp_str)

        #p = re.search(r'[0-9A-Z]{18}',tmp_str).group()#re.search(r'^(\d{18})$|^([A-Z]{18})$',tmp_str).group()
        all_items = []
        if strList is None or len(strList) < 1:
            p = re.compile(r'[0-9A-Z]{17}')
            all_items = re.findall(p, tmp_str)
            print u'解析结果：'
            print all_items
            all_items.insert(0,'x')
            print u'解析结果1：'
            print all_items

        if len(strList)>0:
            self.lineUpdate(strList)
        else:
            print u'无需要打印的内容'
            self.lineUpdate(all_items)


    def mousePressEvent(self, event):
        #print QEvent.FocusOut, 'mousePressEvent', event.type()
        if event.button() == Qt.LeftButton:
            self.dragPosition = event.globalPos() - self.frameGeometry().topLeft()
            QApplication.postEvent(self, QEvent(174))
            event.accept()

    def eventFilter(self,QWidget, event):
        #print QEvent.FocusOut,'eventFilter',event.type()
        # 失去焦点
        if event.type() == QEvent.Leave:
            print 'focus out'
            self.setWindowOpacity(0.5)
            # 注意要有返回值  不然会出 TypeError: invalid result type from mouseoverEvent.eventFilter()
            return False
        # 获得焦点
        if event.type() == QEvent.Enter or event.type() == QEvent.WindowActivate or event.type() == QEvent.ApplicationActivate:
            print 'focus in'
            self.setWindowOpacity(1)
            self.nameLine.selectAll()
            return False
        else:
            # we don't care about other events
            #print 'we dont care about other events'
            return False

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            self.move(event.globalPos() - self.dragPosition)
            event.accept()






if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = ani()
    window.show()
    sys.exit(app.exec_())